<template>
    <div>
        <navtitle title="注册"></navtitle>
        <!-- 表单 -->
        <van-form @submit="onSubmit">
            <van-cell-group inset>
                <!-- 手机号 -->
                <van-field v-model="username" name="username" left-icon="phone" placeholder="&emsp;手机号"
                    :rules="[{ pattern, message: '请填写手机号' }]" />
                <!-- 验证码 -->
                <van-field v-model="sms" name="sms" left-icon="weapp-nav" placeholder="&emsp;验证码"
                    :rules="[{ required: true, message: '请填写验证码' }]" style="align-items: center;">
                    <template #button>
                        <van-button size="small" type="primary" @click="click">发送验证码</van-button>
                    </template>
                </van-field>
                <!-- 密码 -->
                <van-field v-model="password" :type="show ? 'password' : 'text'" name="password" left-icon="lock"
                    placeholder="&emsp;六位及以上数字字母" :rules="[{ required: true, message: '请填写密码' }]"
                    style="align-items: center;">
                    <template #button>
                        <van-button size="small" type="" style="border:none; background-color: #fff;">
                            <van-icon name="eye" style="font-size: 25px;" @click="show = !show" />
                        </van-button>
                    </template>
                </van-field>
            </van-cell-group>
            <div style="margin: 16px;">
                <van-button block type="primary" native-type="submit">
                    注册
                </van-button>
            </div>
        </van-form>
    </div>
</template>

<script setup>
// 标题
import navtitle from '@/components/navtitle.vue';
import { ref } from 'vue';
// 手机号
let pattern = /^1[3-9]\d{9}$/
// 验证码
let sms = ref('')
const click = () => {
    sms.value = Math.floor(Math.random() * 100000)
}
// 明文密文
let show = ref(true)
// 注册
const username = ref('');
const password = ref('');

import { useRouter } from 'vue-router';
const router = useRouter()

import { registerApi } from '@/api/api';
import { showFailToast, showSuccessToast } from 'vant';
const onSubmit = () => {
    registerApi(username.value, password.value).then((res) => {
        console.log(res);
        if (res.data.code == 0) {
            showSuccessToast('注册成功')
            router.push('/login')
        } else {
            showFailToast('注册失败')
        }
    })
}
</script>

<style lang="scss" scoped></style>